package com.cake.liulanxiangzhu.utils;

import com.cake.liulanxiangzhu.pojo.entity.WxOpenid;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;



@ConfigurationProperties(prefix = "jwt")
public class LoginUtil {
    private static String key; //密钥，名称要与application.yml中配的一样
    private static long expiration; //过期时间，名称要与application.yml中配的一样
    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public long getExpiration() {
        return expiration;
    }
    public void setExpiration(long expiration) {
        this.expiration = expiration;
    }


    //获取openid
    public String getOpenId(String code){
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wxecfe0e5477d67845");
        params.put("APPSECRET", "4acaf0b9638d9eff9039faed526737d7");
        params.put("CODE", code);

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={APPSECRET}&js_code={CODE}&grant_type=authorization_code",
                String.class, params);
        String body = responseEntity.getBody();
        WxOpenid object = new Gson().fromJson(body, WxOpenid.class);
        return object.getOpenid();
    }

    //生成token
    public String getToken(String userId ) {
        long curTime = System.currentTimeMillis();
        JwtBuilder builder = Jwts.builder()
                .setId(userId) //使用用户ID
                .setIssuedAt(new Date(curTime)) //设置token创建时间
                .signWith(SignatureAlgorithm.HS256, key); //进行签名，HS256方式，密钥为key
        if (expiration > 0) {
            builder.setExpiration(new Date(curTime + expiration));  //设置token过期时间
        }
        //builder.claim("key1", "value1");  //添加自定义key:value对
        return builder.compact(); //生成token
    }
    //解析token
    public Claims parser(String token) {
        Claims c = Jwts.parser().setSigningKey(key) //设置签名密钥为yyh
                .parseClaimsJws(token).getBody(); //解析token
        return c;
    }




}
